package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RequestMapping("/dish")
@RestController
public class DishController {
    @Autowired
    private DishService dishService;
    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private CategoryService categoryService;

    /**
     * 菜品新增
     * @param dishDto
     * @return
     */
    @PostMapping
    public R save(@RequestBody DishDto dishDto){
        dishService.saveWithFlavor(dishDto);
        return R.success("添加成功");
    }

    /**
     * 菜品信息分页查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R page(int page,int pageSize,String name){
        //创建分页构造器
        Page<Dish> dishPage = new Page<>(page, pageSize);
        Page<DishDto> dishDtoPage = new Page<>();
        //创建条件构造器，并封装模糊查询条件
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        lqw.like(StringUtils.isNotEmpty(name),Dish::getName,name);
        lqw.eq(Dish ::getIsDeleted, 0);
        //条件排序条件
        lqw.orderByDesc(Dish::getUpdateTime);
        //开始查询
        dishService.page(dishPage,lqw);
        //对象拷贝
        BeanUtils.copyProperties(dishPage, dishDtoPage,"records");
        //查询到的records只有菜品分类id：categoryId，没有分类名称
        List<Dish> records = dishPage.getRecords(); //查询列表数据

        //lambda表达式的写法： List<Dish> records ---> List<DishDto> dishDtos
        List<DishDto> dishDtos = records.stream().map((dish) -> {
            Long categoryId = dish.getCategoryId();
            Category category = categoryService.getById(categoryId);
            String categoryName = category.getName();
            DishDto dishDto = new DishDto();
            dishDto.setCategoryName(categoryName);
            BeanUtils.copyProperties(dish, dishDto);
            return dishDto;
        }).collect(Collectors.toList());
        //将List<DishDto>集合数据封装到Page<DishDto>中
        dishDtoPage.setRecords(dishDtos);
        return R.success(dishDtoPage);
    }

    /**
     * 根据id查询菜品数据
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R get(@PathVariable Long id){
        DishDto dishDto = dishService.getByIdWithFlavor(id);
        return R.success(dishDto);
    }

    /**
     * 修改菜品
     * @param dishDto
     * @return
     */
    @PutMapping
    public R update(@RequestBody DishDto dishDto){
        dishService.updateWithFlavor(dishDto);
        return R.success("新增菜品成功");
    }

    /**
     * 删除和批量删除
     * @param ids
     * @return
     */
    @DeleteMapping
    public R deleteDish(@RequestParam List<Long> ids){
        if (ids.isEmpty()){
            return R.error("批量操作，请先选择套餐");
        }
        LambdaUpdateWrapper<Dish> lqw = new LambdaUpdateWrapper<>();
        lqw.set(Dish::getIsDeleted, 1);
        lqw.in(Dish::getId, ids);
        lqw.eq(Dish::getStatus,0);
        boolean update = dishService.update(lqw);

        return update?R.success("删除成功"): R.error("删除失败");
    }

    /**
     * 起售/停售 批量起售/批量停售
     * @param ids
     * @return
     */
    @PostMapping("/status/{status}")
    public R status(@RequestParam List<Long> ids,@PathVariable Integer status){
        LambdaUpdateWrapper<Dish> lqw = new LambdaUpdateWrapper<>();
        lqw.set(Dish::getStatus, status);
        lqw.in(Dish::getId, ids);
        dishService.update(lqw);
        return R.success("操作成功");
    }

    /**
     * 根据分类id查询该分类下的所有菜品集合
     * @param dish
     * @return
     */
    /*@GetMapping("/list")      //改进前
    public R list(Dish dish){
        //构建查询条件
        LambdaUpdateWrapper<Dish> lqw = new LambdaUpdateWrapper<>();
        lqw.eq(dish.getCategoryId()!=null,Dish::getCategoryId,dish.getCategoryId());
        //添加条件，起售商品（状态为1）的菜品
        lqw.eq(Dish::getStatus, 1);
        //添加排序条件
        lqw.orderByDesc(Dish::getSort);
        List<Dish> list = dishService.list(lqw);
        return R.success(list);
    }*/

    //改进后
    @GetMapping("/list")
    public R list(Dish dish){
        //构建查询条件
        LambdaUpdateWrapper<Dish> lqw = new LambdaUpdateWrapper<>();
        lqw.eq(dish.getCategoryId()!=null,Dish::getCategoryId,dish.getCategoryId());
        //添加条件，起售商品（状态为1）的菜品
        lqw.eq(Dish::getStatus, 1);
        lqw.eq(Dish ::getIsDeleted, 0);
        //添加排序条件
        lqw.orderByDesc(Dish::getSort);
        List<Dish> list = dishService.list(lqw);
        // List<Dish>   ---> List<DishDto>
        List<DishDto> dishDtos= new ArrayList<>();
        //遍历 List<Dish> 集合，获取每一个Dish对象，转变成DishDto对象，放入到新的集合 List<DishDto>
        for (Dish dishs : list) {
            DishDto dishDto = new DishDto();
            //1.把dish的属性值copy给dishDto
            BeanUtils.copyProperties(dishs,dishDto);
            //2.查询菜品的口味数据
            // select * from dish_flavor where dish_id = ?
            LambdaUpdateWrapper<DishFlavor> qw1 = new LambdaUpdateWrapper<>();
            qw1.eq(DishFlavor::getDishId,dishs.getId());
            List<DishFlavor> flavors = dishFlavorService.list(qw1);
            //3.将菜品的口味列表 set给 dishDto
            dishDto.setFlavors(flavors);
            //4.将dishDto放入到 dishDtos 集合中
            dishDtos.add(dishDto);
        }
        return R.success(dishDtos);
    }
}
